<template>
    <div class="planewar">
        <div id="planepi" width="500" height="700">
        </div>
        <div class="container" v-if="gameOver">
                <div class="dialog">
                    <p class="once-again">本轮分数：{{score}}分</p>
                    <p class="once-again">真好玩！</p>
                    <p class="once-again">再来一次~~</p>
                    <el-button class="once-again-btn" @click="init">开始</el-button>
                    <el-button type="danger" @click="back_home">退出</el-button>
                </div>
        </div>

        <div class="container" v-if="stop">
            <div class="dialog">
                <p class="once-again">本轮分数：{{score}}分</p>
                <p class="once-again">暂停</p>
                <el-button class="once-again-btn" @click="init">开始</el-button>
                <el-button type="danger" @click="back_home">返回主页</el-button>
            </div>
        </div>

    </div>
</template>

<script>
    import Common from '../components/common'
    import * as PIXI from 'pixi.js'
    import * as Three from 'three'
    const axios=require('axios')
    const randomColor = [
        "#d41313",
        "#e3b200",
        "#e35b00",
        "#00d254",
        "#002ed2",
        "#87c2b9",
        "#703caa",
        "#FFDC35",
        "#93FF93",
        "#d0d0d0"
    ];
    const player_url=require("../assets/planeimg/player.png")
    var bullet_url=require("../assets/planeimg/bullet1.png")
    var pause_url=require("../assets/pause.png")
    var enemy_url=require("../assets/planeimg/enemy1.png")
    var b1_url=require("../assets/planeimg/boom_gif/b1.gif")
    var b2_url=require("../assets/planeimg/boom_gif/b2.gif")
    var b3_url=require("../assets/planeimg/boom_gif/b3.gif")
    var b4_url=require("../assets/planeimg/boom_gif/b4.gif")
    var b5_url=require("../assets/planeimg/boom_gif/b5.gif")
    var b6_url=require("../assets/planeimg/boom_gif/b6.gif")
    var b7_url=require("../assets/planeimg/boom_gif/b7.gif")
    var b8_url=require("../assets/planeimg/boom_gif/b8.gif")
    var b9_url=require("../assets/planeimg/boom_gif/b9.gif")
    var b10_url=require("../assets/planeimg/boom_gif/b10.gif")
    var b11_url=require("../assets/planeimg/boom_gif/b11.gif")
    var Img=new Array(b1_url,b2_url,b3_url,b4_url,b5_url,b6_url,b7_url
        ,b8_url,b9_url,b10_url,b11_url);
    export default {
        name: "Planewar",
        data(){
            return{
                app:'',
                player:'',
                allbullet:[],
                bullet:'',
                enemy:'',
                pause:'',
                allenemy:[],
                boomTextrus:[],
                health:3,
                gameOver:false,
                stop:false,
                username:'',
                i:0,
                record:'',
                crushBalls: [],
                clientWidth:0,
                score:0,
                clientHeight: 0,
                ctx: null,
            }
        },
        mounted(){
            let _this=this
            //_this.username=Common.username
            _this.app=new PIXI.Application({
                width:500,
                height:700,
                transparent: true, //透明
                antialias: true,
                autoDensity: true,
                resolution: devicePixelRatio,
            });
            var container=document.getElementById("planepi")
            container.style.cursor="none"
            container.appendChild(_this.app.view)
            _this.app.stage.interactive=true
            _this.app.stage.hitArea = _this.app.renderer.screen;

            //_this.drawplayer();
            for (let i = 0; i < 11; i++) {
                const texture = PIXI.Texture.from(Img[i]);
                this.boomTextrus.push(texture)
            }
            _this.init()
            this.drawAll();
            _this.drawScore();

            _this.app.stage.on("pointermove",(e)=>{
                _this.player.position.copyFrom(e.data.global);
            });

            document.onkeydown=function(e){
                if(e.keyCode==27){
                    _this.stop=true
                    for(let i=0;i<_this.allenemy.length;i++){
                        const enemy=_this.allenemy[i]
                        enemy.visible=false
                    }
                    _this.allenemy=[]
                }
            }
            _this.movebullet();
            _this.moveEnemy();
            _this.player_Hit();
        },

        methods:{
          init(){
              let _this = this;
              console.log(this.allenemy)
              if(_this.gameOver==true){
                  //location.reload();
                  this.health=3
                  this.send_score();
                  this.score=0
              }
              else {
                  _this.stop = false
              }
              _this.gameOver = false

          },

            drawAll(){
              let _this=this
              _this.drawplayer();
              _this.drawpause();
                setInterval(function () {
                    _this.drawBullet();
                },200)
                setInterval(function () {
                    _this.drawenemy();
                },1000)
                //
              //this.drawScore();
            },

            drawplayer() {
                //const texture=new PIXI.Texture.from(plane_url)
                this.player=PIXI.Sprite.from(player_url)
                this.player.width=80
                this.player.height=80
                //this.plane.x=this.app.screen.width/2-this.plane.width/2
                //this.plane.y=500
                this.player.interactive=true
                this.player.position.set(this.app.renderer.screen.width / 2, 600);
                //this.plane.gotoAndPlay(Math.random()*27)
                //console.log(this.player.position)
                this.app.stage.addChild(this.player)
            },


            drawpause(){
              this.pause=PIXI.Sprite.from(pause_url);
              this.pause.interactive=true;
              this.pause.width=60;
              this.pause.height=80;
              console.log(this.app.renderer.screen.width);
              this.pause.position.set(this.app.renderer.screen.width-60,10);
              this.app.stage.addChild(this.pause)
            },

            drawBullet()
            {
                if(!this.gameOver && !this.stop) {
                    this.bullet = PIXI.Sprite.from(bullet_url)
                    this.bullet.width = 10
                    this.bullet.height = 20
                    this.bullet.dy = 5
                    //console.log(this.plane.position.y)
                    //this.bullet.position.copyFrom(this.plane.position)
                    this.bullet.x = this.player.x + (this.player.width / 2) - 4
                    this.bullet.y = this.player.y
                    this.app.stage.addChild(this.bullet)
                    this.allbullet.push(this.bullet)
                }
                //console.log("子弹"+this.bullet)
                //console.log(this.allbullet[0].position)
            },

            movebullet() {
                this.app.ticker.add(() =>{
                    for(let i=0;i<this.allbullet.length;i++){
                        const bullet=this.allbullet[i]
                        bullet.y-=this.bullet.dy;
                        if(this.allbullet[i].y<=0){
                            //bullet.visible=false
                            //this.app.stage.removeChild(this.allbullet[i])
                            bullet.visible=false
                            this.allbullet.splice(i,1)
                        }
                    }
                })
            },


            drawenemy() {
              if(!this.gameOver && !this.stop) {
                  this.enemy = PIXI.Sprite.from(enemy_url)
                  this.enemy.width = 40
                  this.enemy.height = 40
                  this.enemy.dy = 3
                  this.enemy.position.set(Math.random() * this.app.screen.width, 40)
                  this.app.stage.addChild(this.enemy)
                  this.allenemy.push(this.enemy)
              }
            },

            moveEnemy() {
              const app1=this.app.ticker
                app1.add(() =>{
                    for(let i=0;i<this.allenemy.length;i++){
                        const enemy=this.allenemy[i]
                        enemy.y+=this.enemy.dy
                        if(this.allenemy[i].y>=700){
                            //enemy.visible=false
                            //this.app.stage.removeChild(this.allenemy[i])
                            this.allenemy.splice(i,1)
                            this.allenemy.visible=false
                            //console.log(this.allenemy.length)
                        }
                        for(let j=0;j<this.allbullet.length;j++){
                            const bullet=this.allbullet[j]
                            if(bullet.x>=enemy.x
                                && bullet.x<=enemy.x+30
                                && bullet.y>=enemy.y
                                && bullet.y<=enemy.y+10){
                                //enemy.visible=false
                                this.score++;
                                this.drawScore();
                                this.drawboom(enemy.x,enemy.y)
                                this.app.stage.removeChild(this.allbullet[j])
                                this.allbullet.splice(j,1)
                                bullet.visible=false
                                enemy.visible=false
                                //this.app.stage.removeChild(this.allenemy[j])
                                this.allenemy.splice(i,1)
                                //console.log(this.explosion.visible)
                                // setTimeout(function () {
                                //     this.explosion.visible=false
                                // },200)
                                //this.allbullet[j].visible=false
                            }
                        }
                    }
                });
            },

            drawboom(x,y){
                const explosion = new PIXI.AnimatedSprite(this.boomTextrus);
                this.app.stage.addChild(explosion);
                explosion.x = x
                explosion.y = y
                explosion.anchor.set(0.5);
                explosion.rotation = Math.random() * Math.PI;
                explosion.scale.set(0.75 + Math.random() * 0.5);
                explosion.animationSpeed=0.25
                explosion.play();
                //explosion.play(Math.random()*27)
                explosion.loop=false
                explosion.onComplete=function () {
                    explosion.visible=false
                    //console.log(explosion)
                }
            },

            player_Hit(){
              let _this=this
                    _this.app.ticker.add(() => {
                         if (this.health <= 0) {
                            this.gameOver = true
                            return;
                        } else {
                            for (let i = 0; i < this.allenemy.length; i++) {
                                const enemy = this.allenemy[i]
                                if (this.player.x >= enemy.x && this.player.x <= enemy.x + 40
                                    && this.player.y >= enemy.y && this.player.y <= enemy.y + 50) {
                                    this.health--;
                                    this.score++;
                                    this.drawboom(enemy.x, enemy.y)
                                    this.allenemy.splice(i, 1)
                                    enemy.visible = false
                                }
                            }
                        }

                    })

            },

            back_home(){
                this.send_score();
                this.$router.push("/home");
            },

            send_score(){
                let data=new URLSearchParams()
                data.append('username',this.$cookies.get("username"))
                data.append('planewar',this.score)
                axios.post('/user/updateplanewar',data).then(res =>{
                    console.log(res)
                })
            },

            drawScore(){
                let style = new PIXI.TextStyle({
                    fontFamily: "Arial",
                    fontSize: 15,
                    fill: "white",
                    stroke: '#ff3300',
                    strokeThickness: 4,
                    dropShadow: true,
                    dropShadowColor: "#000000",
                    dropShadowBlur: 4,
                    dropShadowAngle: Math.PI / 6,
                    dropShadowDistance: 6,
                });
                this.record=new PIXI.Text("分数："+this.score,style);
                this.record.x=20;
                this.record.y=20;
                this.app.stage.addChild(this.record);

            },

            getRandomArbitrary(min, max) {
                return Math.random()*(max-min)+min;
            },

            getRandomColor(){
                return randomColor[Math.floor(Math.random() * randomColor.length)];
            },

            getCurshBreaks() {
                let _this = this;
                for (let i = 0; i < 10+_this.score*5; i++) {
                    this.crushBalls.push({
                        x: 5,
                        y: 5,
                        dx: _this.getRandomArbitrary(-6, 6),
                        dy: _this.getRandomArbitrary(-6, 6),
                        r: _this.getRandomArbitrary(1, 4),
                        color: _this.getRandomColor()
                    });
                }
            },

            drawCrushBreaks() {
                this.ctx.clearRect(0, 0, this.clientWidth, this.clientHeight);
                this.crushBalls.forEach(item => {
                    this.ctx.beginPath();
                    this.ctx.arc(item.x, item.y, item.r, 0, 2 * Math.PI);
                    this.ctx.fillStyle = item.color;
                    this.ctx.fill();
                    this.ctx.closePath();
                    item.x += item.dx;
                    item.y += item.dy;
                    if (
                        // 碰到左右墙壁
                        item.x - item.r < 0 ||
                        item.x + item.r > this.clientWidth
                    ) {
                        item.dx = -item.dx;
                    }
                    if (
                        // 碰到上下墙壁
                        item.y - item.r < 0 ||
                        item.y + item.r > this.clientHeight
                    ) {
                        item.dy = -item.dy;
                    }
                });
            },
        }
    }
</script>

<style lang="scss" scoped>

    #planepi{
        background-image: url("../assets/planeimg/background.png");
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        position: absolute;
        animation: bgMove 8s linear infinite;
        @keyframes bgMove {
            0% {
                background-position: 0 0;
            }
            100% {
                background-position: 0 800px;
            }
        }
}
    .container {
        position: absolute;
        top: 0;
        width: 500px;
        height: 700px;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
        text-align: center;
        font-size: 0;
        white-space: nowrap;
        overflow: auto;
    }
    .container:after {
        content: "";
        display: inline-block;
        height: 100%;
        vertical-align: middle;
    }
    .dialog {
        width: 400px;
        height: 300px;
        background: rgba(255, 255, 255, 0.5);
        box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, 0.3);
        display: inline-block;
        vertical-align: middle;
        text-align: left;
        font-size: 28px;
        color: #fff;
        font-weight: 600;
        border-radius: 10px;
        white-space: normal;
        text-align: center;
        .once-again-btn {
            background: #1f9a9a;
            border: none;
            color: #fff;
        }
    }

</style>